package com.sunnay.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunnay.entity.AppUserInfoEntity;
import com.sunnay.enums.GbCodeEnum;
import com.sunnay.exception.DataException;
import com.sunnay.mapper.AppUserInfoMapper;
import com.sunnay.service.AppUserInfoService;
import com.sunnay.vo.auth.LoginAuthVo;
import com.sunnay.vo.auth.LoginVo;
import com.sunnay.vo.auth.SystemUser;
import com.sunnay.vo.user.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AppUserInfoServiceImpl extends ServiceImpl<AppUserInfoMapper, AppUserInfoEntity> implements AppUserInfoService {

    @Value("${sunay.customer-wechat}")
    private String customerWechat;

    @Override
    public LoginAuthVo login(LoginVo loginVo) {
        AppUserInfoEntity userInfo = this.getOne(Wrappers.<AppUserInfoEntity>query().lambda().eq(AppUserInfoEntity::getUserName, loginVo.getUserName()));
        Optional.ofNullable(userInfo).orElseThrow(() ->  new DataException(GbCodeEnum.USER_NOT_FOUND.getKey(),GbCodeEnum.USER_NOT_FOUND.getValue()));
        if(!StringUtils.equals(userInfo.getUserPass(),loginVo.getUserPass()))
            throw new DataException(GbCodeEnum.USER_PASS_NOT_LOGIN.getKey(),GbCodeEnum.USER_PASS_NOT_LOGIN.getValue());
        LoginAuthVo response = new LoginAuthVo();
        UserInfoVo userInfoVo = this.baseMapper.userInfo(userInfo.getId());
        userInfoVo.setCustomerWechat(customerWechat);
        response.setUser(userInfoVo);
        SystemUser systemUser = new SystemUser();
        systemUser.setId(userInfo.getId());
        systemUser.setUserType(userInfoVo.getUserType());
        systemUser.setClient(6);
        systemUser.setWxId(userInfoVo.getWxId());
        response.setSystemUser(systemUser);
        return response;
    }

    @Override
    public UserInfoVo userInfo(SystemUser systemUser) {
        UserInfoVo userInfoVo = this.baseMapper.userInfo(systemUser.getId());
        userInfoVo.setCustomerWechat(customerWechat);

        return userInfoVo;
    }
}
